const Subscription = require('egg').Subscription;
const moment = require('moment');
// const consola = require('consola');

const getScheduleTime = () => {
    return 1 * 60 * 60 * 24;
};

class clearRegisterOverTime extends Subscription {
    // 通过 schedule 属性来设置定时任务的执行间隔等配置
    static get schedule() {
        return {
            interval: `${getScheduleTime()}s`, // 24小时执行间隔
            type: 'worker', // 指定所有的 worker 都需要执行
        };
    }

    // subscribe 是真正定时任务执行时被运行的函数
    async subscribe() {
        const registerList = await this.ctx.app.redis.hgetall('userRegisterTime') || {};
        let reStoreArray = [];
        for (let key in registerList) {
            let time = moment().diff(moment(registerList[key]), 'seconds');
            if (time <= (getScheduleTime())) {
                reStoreArray.push(key);
                reStoreArray.push(registerList[key]);
            }
        }
        await this.ctx.app.redis.del('userRegisterTime');
        reStoreArray.length && await this.ctx.app.redis.hmset('userRegisterTime', reStoreArray);
    }
}

module.exports = clearRegisterOverTime;